package com.dream.common.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

public abstract class ThreadContextUtil {
    private static final Logger log = LoggerFactory.getLogger(ThreadContextUtil.class);
    private static final ThreadLocal<Map<Object, Object>> resources = new ThreadContextUtil.InheritableThreadLocalMap();

    protected ThreadContextUtil() {
    }

    public static HashMap<Object, Object> getResources() {
        return new HashMap<>(resources.get());
    }

    public static void setResources(Map<Object, Object> newResources) {
        if (!CollectionUtils.isEmpty(newResources)) {
            resources.get().clear();
            resources.get().putAll(newResources);
        }
    }

    private static Object getValue(Object key) {
        return resources.get().get(key);
    }

    public static Object get(Object key) {
        if (log.isTraceEnabled()) {
            String msg = "get() - in thread [" + Thread.currentThread().getName() + "]";
            log.trace(msg);
        }

        Object value = getValue(key);
        if (value != null && log.isTraceEnabled()) {
            String msg = "Retrieved value of type [" + value.getClass().getName() + "] for key [" + key + "] " + "bound to thread [" + Thread.currentThread().getName() + "]";
            log.trace(msg);
        }

        return value;
    }

    public static void put(Object key, Object value) {
        if (key == null) {
            throw new IllegalArgumentException("key cannot be null");
        } else if (value == null) {
            remove(key);
        } else {
            resources.get().put(key, value);
            if (log.isTraceEnabled()) {
                String msg = "Bound value of type [" + value.getClass().getName() + "] for key [" + key + "] to thread " + "[" + Thread.currentThread().getName() + "]";
                log.trace(msg);
            }

        }
    }

    private static void remove(Object key) {
        Object value = resources.get().remove(key);
        if (value != null && log.isTraceEnabled()) {
            String msg = "Removed value of type [" + value.getClass().getName() + "] for key [" + key + "]" + "from thread [" + Thread.currentThread().getName() + "]";
            log.trace(msg);
        }

    }

    public static void remove() {
        resources.remove();
    }

    private static final class InheritableThreadLocalMap<T extends Map<Object, Object>> extends InheritableThreadLocal<Map> {
        private InheritableThreadLocalMap() {
        }
        @Override
        protected Map initialValue() {
            return new HashMap<>(20);
        }

        @Override
        protected Map childValue(Map parentValue) {
            return parentValue != null ? (Map)((HashMap)parentValue).clone() : null;
        }
    }
}